import jsonpath
import json
import os

from Common.handle_request import send_requests
from Common.common_test import CommonTest
from Common.handle_data import EnvData, replace_case_by_regular

com_test = CommonTest()


# 获取科目列表
def __Client_List():
    com_test.Login()
    url = "/ExamAPI/Exam/Subject/List"
    handle = {"Content_Type": "application/json", 'token': '#token#', "exam_no": "#exam_no#"}
    data = {"exam_no": "#exam_no#", "e_dbname": "#e_dbname#", "sch_no": ""}
    handle = replace_case_by_regular(handle)
    data = replace_case_by_regular(data)
    resp = send_requests("post", url, data, handle)
    return resp


# 获取模板文件
def __Get_TplInfor(tpl_no):
    url = "/ExamApi/Template/ReadTplInfor"
    handle = {"Token": "token#"}
    data = {"e_dbname": "#e_dbname#", "exam_no": "#exam_no#", "tpl_group": "0", "tpl_no": tpl_no}
    handle = replace_case_by_regular(handle)
    data = replace_case_by_regular(data)
    Tpl = send_requests("post", url, data, handle)
    return Tpl


# 获取模板图片
def __Get_PicList_img(tpl_no):
    url = "/ExamApi/Template/PicList"
    handle = {"Token": "token#"}
    data = {"e_dbname": "#e_dbname#", "exam_no": "#exam_no#", "tpl_group": "0", "tpl_no": tpl_no}
    handle = replace_case_by_regular(handle)
    data = replace_case_by_regular(data)
    Tpl_img = send_requests("post", url, data, handle)
    return Tpl_img


# 把获取到的数据进行拼接
def Get_json_data(tpl_no):
    # 获取模板文件
    Tpl = __Get_TplInfor(tpl_no)
    # 获取模板图片
    Tpl_img = __Get_PicList_img(tpl_no)

    data_dict = {}
    images = []
    tplInfo = jsonpath.jsonpath(Tpl.json(), "$..tplInfo")[0]
    json_data = jsonpath.jsonpath(Tpl.json(), "$..datas")[0]
    images_data = jsonpath.jsonpath(Tpl_img.json(), "$..datas[*]")
    if json_data and tplInfo:
        data_dict['tplInfo'] = tplInfo
        data_dict['datas'] = json_data

        for img in images_data:
            image = {}
            inpage = jsonpath.jsonpath(img, "inpage")
            pcontent = jsonpath.jsonpath(img, "pcontent")
            image['inpage'] = inpage[0]
            image['pcontent'] = pcontent[0]
            images.append(image)

        data_dict['images'] = images
        return data_dict


# 输出json文件
def Grt_Client_List():
    Get_List = jsonpath.jsonpath(__Client_List().json(), "$..datas[*]")
    for km_list in Get_List:
        esub_name = km_list['esub_name']
        esub_no = km_list['esub_no']
        data_dict = Get_json_data(esub_no)
        if data_dict is not None:
            json.dump(data_dict,
                      open(os.path.join(r"H:\dtk_data", "{}-{}.json").format(getattr(EnvData, "exam_no"), esub_name),
                           'w'))


if __name__ == '__main__':
    Grt_Client_List()
